import type { IArrayItem, ITreeNode } from '../../type';

/**
 * 判断字符串是否为空
 * @param str 字符串
 * @returns boolean
 */
function strIsEmpty(str: string | null | undefined) {
  // 如果字符串为空、null或undefined，则返回true，否则返回false
  return str === '' || str === null || str === undefined;
}

export function listToTree<T extends IArrayItem>(
  list: T[],
  rootId: string | null = null
) {
  const root: T[] = [];
  const lookup: Record<string, T[]> = {};
  list.forEach((item) => {
    lookup[item._id] = [];
  });

  list.forEach((item) => {
    if (!strIsEmpty(item.parentId)) {
      lookup[item.parentId].push(item);
    } else {
      root.push(item);
    }
  });

  function buildTree(arr: T[]) {
    return arr.map((item) => {
      return {
        ...item,
        children: buildTree(lookup[item._id])
      };
    });
  }

  return buildTree(root);
}
